<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo, postPage, putPage } from '#/api/portal/page';
import { usePreferencesStore } from '#/store';

const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? $t('page.common.Add')+' '+`${routeTitle}`
    : `No.${index.value} - `+$t('page.common.Edit')+' '+`${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_title: '',
    post_alias: '',
    more: {
      thumbnail: '',
    },
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.post_title;
          state.form.more.thumbnail = values.thumbnail;
          state.form.post_content = values.post_content;
          state.form.post_title = values.post_title;
          state.form.thumbnail = values.thumbnail;
          state.form.post_alias = values.post_alias;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'post_title',
          'thumbnail',
          'post_content',
          'post_alias',
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: 'required',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      dependencies: {
        trigger: (values, form) => {
          if (values.post_title && !values.id) {
            const alias = pinyin(values.post_title, {
              pattern: 'first',
              toneType: 'none',
            }).replaceAll(/\s+/g, '');
            form.setFieldValue('post_alias', alias);
          }
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['post_title'],
      },
      fieldName: 'post_alias',
      label: $t('page.common.Slug'),
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'thumbnail',
      label: $t('page.common.Thumbnail'),
    },
    {
      component: 'Editor',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_content',
      label: $t('page.common.Content'),
    },
  ],
});

const [SeoForm, SeoFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'seo_title',
      label: 'SEO '+ $t('page.common.Title'),
      dependencies: {
        trigger: (value) => {
          state.form.post_excerpt = value.post_excerpt;
          state.form.more.seo_title = value.seo_title;
          state.form.more.seo_keywords = value.seo_keywords;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['seo_title', 'seo_keywords', 'post_excerpt'],
      },
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'seo_keywords',
      label: 'SEO '+$t('page.common.Keywords'),
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_excerpt',
      label: 'SEO '+$t('page.common.Description'),
    },
  ],
});

const [TemplateForm, TemplateFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: 1,
      dependencies: {
        trigger: (value) => {
          state.form.more.form_id = value.form_id;
          state.form.more.template = value.template;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['form_id', 'template'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'form_id',
      label: $t('admin.formNumber'),
    },
    {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Select'),
      },
      fieldName: 'template',
      label: $t('admin.pageTemplate'),
    },
  ],
});

async function onSubmit() {
  function showMsg(msg: string) {
    message.success(msg);
    closeCurrentTab();
  }
  const values: any = state.form;

  if (values.id) {
    const { msg } = await putPage(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postPage(values);
    showMsg(msg);
  }
}
async function onGetPage(id: number) {
  const { data } = await getPageInfo({ id });
  data.post = {
    id: data.post?.id ?? undefined,
    post_title: data.post?.post_title ?? '',
    post_alias: data.post?.post_alias ?? '',
    post_content: data.post?.post_content ?? '',
    post_keywords: data.post?.post_keywords ?? '',
    post_excerpt: data.post?.post_excerpt ?? '',
    post_hits: data.post?.post_hits ?? 0,
    post_source: data.post?.post_source ?? '',
    published_time:
      data.post?.published_time ?? dayjs().format('YYYY-MM-DD HH:mm:ss'),
    is_top: data.post?.is_top,
    recommended: data.post?.recommended,
    thumbnail: data.post?.thumbnail ?? '',
    categories: data.post?.categories ?? [],
    more: {
      seo_title: data.post?.more?.seo_title ?? '',
      seo_keywords: data.post?.more?.seo_keywords ?? '',
      thumbnail: data.post?.more?.thumbnail ?? '',
      template: data.post?.more?.template ?? '',
      price: data.post?.more?.form_id
        ? Number.parseInt(data.post.more.form_id)
        : 1,
    },
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form, ...state.form.more });
  SeoFormApi.setValues({ ...state.form, ...state.form.more });
  TemplateFormApi.setValues({ ...state.form, ...state.form.more });
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  await onGetPage(index.value);
});
</script>

<template>
  <Page>
    <Card :title="routeTitle+$t('page.common.Details')">
      <Tabs v-model:active-key="activeKey">
        <TabPane key="1" force-render :tab="$t('page.common.Basic Information')">
          <BasicForm />
        </TabPane>
        <TabPane key="2" :disabled="disabled" :tab="$t('page.common.SEO Settings')">
          <SeoForm />
        </TabPane>
        <TabPane key="3" :disabled="disabled" :tab="$t('page.common.Other Options')" >
          <TemplateForm>
            <template #template="slotProps">
              <Select v-bind="slotProps" style="width: 100%">
                <SelectOption
                  v-for="item in state.pageThemeFiles"
                  :key="item.id"
                  :value="item.file"
                >
                  {{ `${item.name} ${item.file}` }}
                </SelectOption>
              </Select>
            </template>
          </TemplateForm>
        </TabPane>
      </Tabs>
    </Card>
  </Page>
</template>
